package trader

import (
	"errors"
	"kubequant/apps/cta"
	"kubequant/gateways"
)

func NewMainEngine() *MainEngine {
	mainEngine := new(MainEngine)
	mainEngine.Engines = make(map[string]BaseEngine) //创建engines map
	mainEngine.Apps = make(map[string]BaseApp)
	mainEngine.Gateways = make(map[string]BaseGateway) //创建gateways map
	mainEngine.InitEngines()
	return mainEngine
}

type MainEngine struct {
	Gateways  map[string]BaseGateway //gateways
	Engines   map[string]BaseEngine  //engines
	Apps      map[string]BaseApp     //apps
	Exchanges []string               //exchanges
}

// InitEngines 初始化所有引擎
func (mainEngine *MainEngine) InitEngines() {
	//添加log engine
	mainEngine.AddEngine("log")
}

// AddEngine 主引擎添加引擎
func (mainEngine *MainEngine) AddEngine(name string) (BaseEngine, error) {
	switch name {
	case "cta":
		engine := cta.NewEngine()
		mainEngine.Engines["cta"] = engine
		return engine, nil
	case "log":
		engine := NewLogEngine()
		mainEngine.Engines["log"] = engine
		return engine, nil
	}
	return nil, errors.New("引擎不存在：" + name)
}

// AddApp 主引擎添加App
func (mainEngine *MainEngine) AddApp(name string) (BaseEngine, error) {
	switch name {
	case "cta":
		app := cta.NewApp()
		mainEngine.Apps[name] = app
		engine, err := mainEngine.AddEngine(name)
		if err != nil {
			return nil, err
		}
		return engine, nil
	}
	return nil, errors.New("App不存在:" + name)
}

// AddGateway 主引擎添加gateway
func (mainEngine *MainEngine) AddGateway(name string) BaseGateway {
	switch name {
	case "ctp":
		gateway := gateways.NewCtpGateway()
		for _, exchange := range gateway.Exchanges {
			mainEngine.Exchanges = append(mainEngine.Exchanges, exchange)
		}
		return gateway
	}
	return nil
}

func (mainEngine *MainEngine) GetEngine(name string) (BaseEngine, error) {
	engine, isOK := mainEngine.Engines[name]
	if isOK {
		return engine, nil
	} else {
		return nil, errors.New("未找到引擎：" + name)
	}
}
